package com.alei.redis.redisdemo.controller;

import com.alei.redis.redisdemo.bean.Commodity;
import com.alei.redis.redisdemo.bean.User;
import com.alei.redis.redisdemo.bean.dto.CartDto;
import com.alei.redis.redisdemo.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author ShiLei
 * @version v1.0
 * @date 2020-06-27 18:41
 */
@RestController
public class RedisHashDemoController {

    /**
     * 注入 redis 客户端连接池
     */
    @Resource
    private JedisPool jedisPool;
    @Resource
    private UserService userService;

    /**
     * hash 购物车实现
     */
    @RequestMapping("testCart")
    public Object testCart(@RequestBody CartDto cartDto) {
        Jedis jedis = null;

        try {
            User user = userService.getUserById(cartDto.getUserId());
            Commodity comm = userService.getCommById(cartDto.getCommId());
            //获取jedis实例
            jedis = jedisPool.getResource();
            String key = "user:" + user.getId() + ":cart";
            String num = jedis.hget(key, comm.getId() + "");
            Long count;
            if (StringUtils.isEmpty(num)) {
                //购物车：user:userId:cart 为key、商品id为field、商品数量为value
                count = jedis.hset(key, comm.getId() + "", cartDto.getCommNum() + "");
            } else {
                //购物车：user:userId:cart 为key、商品id为field、商品数量为value
                count = jedis.hset(key, comm.getId() + "", (cartDto.getCommNum() + Integer.valueOf(num)) + "");
            }
            if (count > 0) {
                System.out.println("放入缓存成功");
                //做对应操作
            }
            Map<String, String> map = jedis.hgetAll(key);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }

    /**
     * hash 存储对象
     */
    @RequestMapping("testObject")
    public Object testObject() {
        User user = new User();
        user.setName("张三");
        user.setAddress("北京");
        Jedis resource = jedisPool.getResource();
        resource.hset("userInfo", "name", user.getName());
        resource.hset("userInfo", "address", user.getAddress());
        String name = resource.hget("userInfo", "name");
        String address = resource.hget("userInfo", "address");
        System.out.println("用户姓名为：" + name + ",地址为：" + address);
        return resource.hgetAll("userInfo");
    }
}
